/** 上传文件模块  */
import { toLoginPage, CacheUtils, mergeObject, } from "./index.js";

const getUploadUrl = ()=>{
	// #ifdef H5
		return '/server/'+'fsfileupload&userid='+CacheUtils.get('userid')
	// #endif
	
	return import.meta.env.VITE_SERVER_HOST + 'fsfileupload&userid=' + CacheUtils.get('userid')
}

/** 选择头像并上传 */
export const chooseAndUploadPortrait = ()=>{
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			success(res) {
				const uploadPath = res.tempFilePaths&&res.tempFilePaths[0];
				uploadHeaderImage(uploadPath).then((res)=>resolve(res)).catch((err)=>reject('operate fail:'+err))
			},
			fail(err) {
				console.error('choose image error: ', err);
				reject('choose image error');
			},
		})
	});
}


// 上传头像方法
export const uploadHeaderImage = (filePath) => {
	 
	return new Promise((resolve, reject) => {
		uni.showLoading({
			mask: true
		});

		let userid = uni.getStorageSync('user').userid;
		if (!userid) {
			userid = '';
		}

		uni.uploadFile({
			url: getUploadUrl(),
			filePath: filePath,
			name: 'file',
			formData: {
				userid: userid
			},
			success: (res) => {
				const resule = JSON.parse(res.data);
				resolve(resule); // 上传成功后，resolve 结果
			},
			fail: (err) => {
				console.error('上传失败:', err);
				reject(err); // 上传失败后，reject 错误
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
};

